import Vapor
import Fluent 

struct UserController: RouteCollection {
    // 注册路由
    /*
    数据转换： 
    1. 使用 User 模型中的 toDTO() 方法将数据库模型转换为 DTO
    2. 使用 UserDTO 中的 toModel() 方法将请求数据转换为数据库模型
    */

    // 通过 boot 方法注册所有用户相关的路由 
    func boot(routes: any RoutesBuilder) throws {
        // 基础路径为 "/users"
        let users = routes.grouped("api", "users")
        
        //私有路由（需要 JWT 认证）
        let protected = users.grouped(UserAuthenticator(), UserPayload.guardMiddleware())
        
        // 用户相关操作
        registerUserRoutes(users: protected)
        // 密码相关操作
        registerPasswordRoutes(users: protected)
    }
}
//用户相关操作
extension UserController{
    //    注册用户相关操作路由
    func registerUserRoutes(users:  any RoutesBuilder) {
        users.get("getAllUsers",use: getAllUsers)
        users.get("getUser", use: getUser)
        users.post("updateUser", use: updateUser)
    }
    
    // 获取所有用户
    func getAllUsers(req: Request) async throws -> ApiResponse<[UserDTO]> {
        do {
            let users = try await User.query(on: req.db).all()
            return ApiResponse.success(data: users.map { $0.toDTO() })
        } catch  {
            return ApiResponse.success(data: [])
        }
    }
    
    // 获取单个用户
    func getUser(req: Request) async throws -> ApiResponse<UserDTO> {
        let user =  try await UserPayload.getCurrentUserFromToken(req: req)
        return ApiResponse.success(data: user.toDTO())
    }
     
    // 更新现有用户
    func updateUser(req: Request) async throws -> ApiResponse<EmptyContent> {
        let requestData = try req.content.decode(UpdateUserDTO.self)
        guard let userId = requestData.userId else {
            throw Abort.requestParametersError
        }
        guard let user = try await User.find(UUID(uuidString: userId.value), on: req.db) else {
            throw Abort.userNotExist
        }
        if let name = requestData.name {
            user.name = name
        }
        if let age = requestData.age {
            user.age = age
        }
        if let phone = requestData.phone {
            user.phone = phone
        }
        try await user.save(on: req.db)
        return ApiResponse.success()
    }
     
}

//密码相关操作
extension UserController{
    func registerPasswordRoutes(users:  any RoutesBuilder) {
        users.post("configPwd",use: configPwd)
    }
    
    // 设置用户密码
    func configPwd(req: Request) async throws -> ApiResponse<EmptyContent> {
        let requestData = try req.content.decode(ConfigPwdDTO.self)
        guard let userId =  requestData.userId,let newPassword = requestData.password, !newPassword.isEmpty else {
            throw Abort.requestParametersError
        }
        guard let user = try await User.find(UUID(uuidString: userId.value), on: req.db) else {
            throw Abort.userNotExist
        }
        // 使用 SHA256 哈希算法对密码进行哈希处理 BCrypt在哈希的过程中会自动加盐
        let hash =  try req.password.hash(newPassword)
        user.passwordHash = hash.base64String()
        try await user.save(on: req.db) // 保存更新后的用户信息
        return ApiResponse.success()
    }
    
    
}
